const store = require('./storage')

const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const getDate = () => {
    let date = new Date()
    const year = date.getFullYear()
    let month = date.getMonth() + 1
    let day = date.getDate()
    if (month < 10) {
        month = '0' + month
    }
    if (day < 10) {
        day = '0' + day
    }
    return `${year}-${month}-${day}`
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}

/**
 * promise节流函数
 * @param {*} foo 
 * @param {Number} 延迟resolved时间
 */
const only = function(foo, delay = 0) {
    var isResolved = true
    return function() {
        const args = [...arguments];
        if (isResolved) {
            return new Promise((resolve, reject) => {
                isResolved = false
                foo.apply(this, args).then(res => {
                    if (!delay) {
                        resolve(res);
                        isResolved = true;
                    } else {
                        setTimeout(() => {
                            resolve(res);
                            isResolved = true;
                        }, delay)
                    }

                }).catch(e => { reject(e);
                    isResolved = true; })
            })
        } else {
            return Promise.reject('ERROR_PROMISE_LOADING')
        }
    }
}

//多次调用promise只用最新的
const useLatest = function(foo) {
    //promise队列
    let queue = []
    let isResolved = true
    let ret
    return function() {
        //加入一个到队列
        queue.push(foo.apply(this, [...arguments]))
            // console.log('aaa', queue)
            // setTimeout(()=>{console.log(queue)}, 6000)
        if (isResolved) {
            isResolved = false
            ret = new Promise(function(resolve, reject) {
                //从队列头部取出一个
                var run = function() {
                    let promise = queue.shift()

                    //递归去调用promise，直到队列没有数据
                    promise.then(res => {
                        // console.log('qqq', queue)
                        if (queue.length === 0) {
                            resolve(res)
                            isResolved = true
                        } else {
                            run()
                        }
                    }).catch(e => {
                        if (queue.length === 0) {
                            isResolved = true
                            throw new Error(e)

                        } else {
                            run()
                        }
                    })
                }

                run()
            })
            return ret
        } else {
            return ret
        }
    }
}


/**
 * 缓存请求的pormise,用于预加载
 */
const cachePromise = function(promiseMaker) {
    //缓存
    let promiseCache = null
    return function(refresh = false) {
        //缓存没数据或者refresh为真就重新获取promise
        if (!promiseCache || refresh) {
            promiseCache = promiseMaker()
        }
        return promiseCache
    }
}


/**
 * 获取unionid，如果本地存储没有，则去等待loginPromise
 */
var getUnionid = () => {
    return new Promise((resolve, reject) => {
        const { unionid } = store.get()
        if (unionid) {
            resolve(unionid)
        } else if (global.loginPromise) {
            global.loginPromise.then(res => {
                var rt = res;
                // debugger
                // if (rt.code == 0) {
                const { unionid } = rt
                resolve(unionid)
                    // // }else {
                    //     reject('Unionid Invalid.')
                    // }
            })
        } else {
            reject('Unionid Invalid.')
        }
    })
}

//问答cachePromise
// var foo = function() {
//     return new Promise((resolve, reject)=>{
//         setTimeout(()=>resolve(12), 2000)
//     })
// }

// const a = cachePromise(foo)

// a().then(res=>console.log(res))

// a().then(res=>console.log(res))

// setTimeout(()=>{
//     a().then(res=>console.log(res))
// },2100)

// setTimeout(()=>{
//     a(true).then(res=>console.log(res))
// },2300)


// 问答代码
// const makePromise = function() {
//     return new Promise((resolve,reject)=>{
//         setTimeout(()=>{
//             let a = new Date().getTime()
//             console.log(a)
//             resolve(a)
//         }, 5000)
//     })
// }

// const b = useLatest(makePromise)

// var c = b()

// setTimeout(()=>{console.log('c', c)}, 1000)

// // b().then(res=>console.log('res', res))

// setTimeout(()=>{console.log('c', c)}, 6000)

// setTimeout(()=>{b().then(res=>console.log('res', res))}, 7000)

// setTimeout(()=>{console.log('c', c)}, 8000)

module.exports = {
    formatTime: formatTime,
    only,
    useLatest,
    cachePromise,
    getDate,
    getUnionid
}